package com.example.peibei.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.TextView;

import com.alipay.sdk.app.OpenAuthTask;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.BindAliPayPresenter;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class BindPayAccountActivity extends WDActivity {
    @BindView(R.id.tv_zfb)
    TextView tv_zfb;
    @BindView(R.id.tv_wx)
    TextView tv_wx;

    private SPUtils spUtils;
    private String token;
    private String zfbId;
    private String wxId;
    private BindAliPayPresenter bindAliPayPresenter;
    private IWXAPI api;
    private static final String APP_ID = "wx4de7acf350b321e9";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_pay_account;
    }

    @Override
    protected void initView() {
        spUtils = new SPUtils(BindPayAccountActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        bindAliPayPresenter = new BindAliPayPresenter(new BindAliPayCall());
    }

    @Override
    protected void onResume() {
        super.onResume();
        zfbId = spUtils.getString(SpConstant.ZFB_ID);
        wxId = spUtils.getString(SpConstant.WX_ID);
        if (zfbId.equals("false")) {
            tv_zfb.setText("未绑定");
        } else {
            tv_zfb.setText("已绑定");
        }
        if (wxId.equals("false")) {
            tv_wx.setText("未绑定");
        } else {
            tv_wx.setText("已绑定");
        }
    }

    @OnClick(R.id.rl_zfb)
    public void bindZfb() {
        if (zfbId.equals("false")) {
            openAuthScheme();
        } else {
            UIUtils.showToastSafe("支付宝已绑定");
        }
    }

    @OnClick(R.id.rl_wx)
    public void bindWx() {
        if (wxId.equals("false")) {
            UIUtils.showToastSafe("微信绑定暂未开通");
        } else {
            UIUtils.showToastSafe("支付宝已绑定");
        }
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    /**
     * 通用跳转授权业务 Demo
     */
    public void openAuthScheme() {
        // 传递给支付宝应用的业务参数
        final Map<String, String> bizParams = new HashMap<>();
        bizParams.put("url", "https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id=2021003100616464&scope=auth_user&state=init");
        // 支付宝回跳到您的应用时使用的 Intent Scheme。
        // 请设置为一个不和其它应用冲突的值，并在 AndroidManifest.xml 中为 AlipayResultActivity 的 android:scheme 属性
        // 指定相同的值。实际使用时请勿设置为 __alipaysdkdemo__ 。
        // 如果不设置，OpenAuthTask.execute() 在用户未安装支付宝，使用网页完成业务流程后，将无法回跳至您的应用。
        final String scheme = "__alipaysdkdemo__";
        // 防止在支付宝 App 被强行退出等意外情况下，OpenAuthTask.Callback 一定时间内无法释放，导致
        // Activity 泄漏
        final WeakReference<Activity> ctxRef = new WeakReference<>(this);
        // 唤起授权业务
        final OpenAuthTask task = new OpenAuthTask(this);
        task.execute(
                scheme,    // Intent Scheme
                OpenAuthTask.BizType.AccountAuth, // 业务类型
                bizParams, // 业务参数
                new OpenAuthTask.Callback() {
                    @Override
                    public void onResult(int i, String s, Bundle bundle) {
                        final Context ref = ctxRef.get();
                        if (ref != null) {
//                            showAlert(ref, String.format("结果码: %s\n结果信息: %s\n结果数据: %s", i, s, bundleToString(bundle)));
                            String auth_code = bundle.get("auth_code").toString();
                            bindAliPayPresenter.reqeust("Bearer " + token, auth_code);
                            spUtils.putString(SpConstant.AUTH_CODE, auth_code);
                        }
                    }
                }, // 业务结果回调
                true); // 是否需要在用户未安装支付宝 App 时，使用 H5 中间页中转。建议设置为 true。
    }

    private static String bundleToString(Bundle bundle) {
        if (bundle == null) {
            return "null";
        }
        final StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            sb.append(key).append("=>").append(bundle.get(key)).append("\n");
        }
        return sb.toString();
    }

    class BindAliPayCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("绑定支付宝成功");
            zfbId = "true";
            spUtils.putString(SpConstant.ZFB_ID, zfbId);
            tv_zfb.setText("已绑定");
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton("确定", null)
                .setOnDismissListener(onDismiss)
                .show();
    }

    @Override
    protected void destoryData() {

    }
}
